using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPoco;
using SrBBSPro.Entities;

namespace SrBBSPro.BaseClasses
{
    public class BaseService<T, TId> where T : BaseEntity<TId>
    {
        protected Database DbBase { get; }

        public BaseService()
        {
            DbBase = new Database("constr");
        }

  
        protected bool IsInsertSuccess(object val)
        {
            return (val.GetType() == typeof(System.String) && val != null
                || Convert.ToInt64(val) > 0);
        }

        protected bool IsUpdateSuccess(int val)
        {
            return val > 0;
        }

        public Response Insert(T entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));
            var response = new Response();

            try
            {
                using (var transaction = DbBase.GetTransaction())
                {
                    var result = DbBase.Insert(entity);
                    if (IsInsertSuccess(result))
                    {
                        response.IsSuccess = true;
                        response.Message = "操作成功";
                    }
                    else
                    {
                        response.Message = "操作失败";
                    }
                    transaction.Complete();
                }
            }
            catch
            {
                response.Message = "操作失败";
            }              
            return response;
        }

        public Response Update(T entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));
            var response = new Response();
            try
            {
                using (var transaction = DbBase.GetTransaction())
                {
                    var result = DbBase.Update(entity);
                    if (result > 0)
                    {
                        response.IsSuccess = true;
                        response.Message = "操作成功";
                    }
                    else
                    {
                        response.Message = "操作失败";
                    }
                    transaction.Complete();
                }
            }
            catch
            {
                response.Message = "操作失败";
            }           
            return response;
        }


        public T GetSingleEntity(TId id)
            => DbBase.Query<T>().SingleOrDefault(t => t.Id.Equals(id));

        public List<T> GetLimitList(List<T> li, out int count, int page)
        {
            page = page < 1 ? 1 : page;
            count = li.Count;
            return li.Skip((page - 1) * 10).Take(10).ToList();
        }

        public virtual Response InsertOrUpdate(object obj)
        {
            var response = new Response();
            var entity = Activator.CreateInstance<T>();
            if (obj == null)
                throw new ArgumentNullException(nameof(entity));
            try
            {
                long reslut = 0; 
                entity.SetProp(obj);
                using (var transaction = DbBase.GetTransaction())
                {
                    if (GetSingleEntity(entity.Id) == null)
                    {
                        reslut=  Convert.ToInt64(DbBase.Insert(entity));
                    }
                    else
                    {
                        reslut=DbBase.Update(entity);
                    }
                    if (reslut > 0)
                    {
                        response.IsSuccess = true;
                        response.Message = "操作成功";
                    }
                    else
                    {
                        response.Message = "操作失败";
                    }
                    transaction.Complete();
                }
            }
            catch
            {
                response.Message = "操作失败";
            }
            return response;
        }      

        public List<User> GetUserList(string depart)
        {
            if (string.IsNullOrEmpty(depart))
            {
                return DbBase.Query<User>().ToList();
            }
            else
            {
                return DbBase.Query<User>().Where(u => u.Depart == depart).ToList();
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public User GetUserInfo(string userId)
            => DbBase.SingleOrDefaultById<User>(userId);

        public Response DelEntityById(TId Id)
        {
            var res = new Response();
            try
            {              
                using (var tran = DbBase.GetTransaction())
                {
                    var num = DbBase.Delete<T>(Id);
                    tran.Complete();
                    if (IsUpdateSuccess(num))
                    {
                        res.IsSuccess = true;
                        res.Message = "删除成功";
                    }
                }
            }
            catch
            {
                res.IsSuccess = false;
                res.Message = "删除失败";
            }
            return res;
        }
    }

}
